<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


  
  
  <link rel="stylesheet" href="/xieyuanhui/lib/needsharebutton/needsharebutton.css">

















  
  
  <link rel="stylesheet" href="/xieyuanhui/lib/fancybox/source/jquery.fancybox.css">







<link rel="stylesheet" href="/xieyuanhui/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/xieyuanhui/css/main.css?v=7.1.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/xieyuanhui/images/apple-touch-icon-next.png?v=7.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/xieyuanhui/images/favicon-32x32-next.png?v=7.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/xieyuanhui/images/favicon-16x16-next.png?v=7.1.0">


  <link rel="mask-icon" href="/xieyuanhui/images/logo.svg?v=7.1.0" color="#222">


  <link rel="manifest" href="/xieyuanhui/images/manifest.json">


  <meta name="msapplication-config" content="/xieyuanhui/images/browserconfig.xml">





<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/xieyuanhui/',
    scheme: 'Pisces',
    version: '7.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="原文地址：深入理解 Java Object Java中的Object对象为所有对象的直接或间接父对象，里面定义的几个方法容易被忽略却非常重要。以下来自Effective Java 对Object中几个关键方法的应用说明. 12345678910111213141516171819202122232425262728package common;/** * @author LitheLight *">
<meta name="keywords" content="Object">
<meta property="og:type" content="article">
<meta property="og:title" content="深入理解Java Object">
<meta property="og:url" content="http://xyh5513.gitee.io/xieyuanhui/2019/08/05/深入理解Java-Object/index.html">
<meta property="og:site_name" content="xieyuanhui的笔记">
<meta property="og:description" content="原文地址：深入理解 Java Object Java中的Object对象为所有对象的直接或间接父对象，里面定义的几个方法容易被忽略却非常重要。以下来自Effective Java 对Object中几个关键方法的应用说明. 12345678910111213141516171819202122232425262728package common;/** * @author LitheLight *">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-08-05T14:24:35.117Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="深入理解Java Object">
<meta name="twitter:description" content="原文地址：深入理解 Java Object Java中的Object对象为所有对象的直接或间接父对象，里面定义的几个方法容易被忽略却非常重要。以下来自Effective Java 对Object中几个关键方法的应用说明. 12345678910111213141516171819202122232425262728package common;/** * @author LitheLight *">



  <link rel="alternate" href="/xieyuanhui/atom.xml" title="xieyuanhui的笔记" type="application/atom+xml">



  
  
  <link rel="canonical" href="http://xyh5513.gitee.io/xieyuanhui/2019/08/05/深入理解Java-Object/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>深入理解Java Object | xieyuanhui的笔记</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript><!-- hexo-inject:begin --><!-- hexo-inject:end -->

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <!-- hexo-inject:begin --><!-- hexo-inject:end --><div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/xieyuanhui/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xieyuanhui的笔记</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/xieyuanhui/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/xieyuanhui/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/xieyuanhui/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/xieyuanhui/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/xieyuanhui/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://xyh5513.gitee.io/xieyuanhui/xieyuanhui/2019/08/05/深入理解Java-Object/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xieyuanhui">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/xieyuanhui/images/deer.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xieyuanhui的笔记">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">深入理解Java Object

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-08-05 17:13:11 / 修改时间：22:24:35" itemprop="dateCreated datePublished" datetime="2019-08-05T17:13:11+08:00">2019-08-05</time>
            

            
              

              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/xieyuanhui/categories/Java基础/" itemprop="url" rel="index"><span itemprop="name">Java基础</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          
            <span id="/xieyuanhui/2019/08/05/深入理解Java-Object/" class="leancloud_visitors" data-flag-title="深入理解Java Object">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              
                <span class="post-meta-item-text">阅读次数：</span>
              
                <span class="leancloud-visitors-count"></span>
            </span>
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">9.1k</span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">8 分钟</span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>原文地址：<a href="https://www.jianshu.com/p/4222abe52c12" target="_blank" rel="noopener">深入理解 Java Object</a></p>
<p>Java中的Object对象为所有对象的直接或间接父对象，里面定义的几个方法容易被忽略却非常重要。以下来自Effective Java 对Object中几个关键方法的应用说明.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> common;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> LitheLight</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/8/5</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PhoneNumber</span> <span class="keyword">implements</span> <span class="title">Cloneable</span>, <span class="title">Comparable</span>&lt;<span class="title">PhoneNumber</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">short</span> linNum, prefix, areaCode;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">PhoneNumber</span><span class="params">(<span class="keyword">short</span> number, <span class="keyword">short</span> prefix, <span class="keyword">short</span> areaCode)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.linNum = rangeCheck(number, <span class="number">999</span>, <span class="string">"linNum"</span>);</span><br><span class="line">        <span class="keyword">this</span>.prefix = rangeCheck(prefix, <span class="number">999</span>, <span class="string">"prefix"</span>);</span><br><span class="line">        <span class="keyword">this</span>.areaCode = rangeCheck(areaCode, <span class="number">999</span>, <span class="string">"areaCode"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">short</span> <span class="title">rangeCheck</span><span class="params">(<span class="keyword">int</span> val, <span class="keyword">int</span> max, String arg)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (val &lt; <span class="number">0</span> || val &gt; max) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(arg + <span class="string">":"</span> + val);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> (<span class="keyword">short</span>)val;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compareTo</span><span class="params">(PhoneNumber o)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="equals-Object-o"><a href="#equals-Object-o" class="headerlink" title="equals(Object o)"></a>equals(Object o)</h3><p>Object中equals方法的实现仅仅是比较了两个对象的地址，对于某些类来说正是所需用的、毋需复写的</p>
<ul>
<li>Thread,由于每个线程对象天生就是独一无二的，重点表达是实体而不是值，不需要比较</li>
<li>java.util.regex.Pattern，正则表达式的类型也没有比较实例是否相同的必要</li>
<li>父类复写了equals方法，并且是子类所需要的，如AbstractSet，AbstractList，AbstractMap，其子类毋需复写。</li>
<li>private或package private修饰的类，其方法不会被调用</li>
</ul>
<p>什么时候需要对类的equals方法复写？</p>
<p>当一个类表示一个值，如String、Integer；它的不同实例需要逻辑上判断是否相同，而不仅仅是地址是否相同，此时需要复写来自定义相等的条件。由于Map的键和Set的元素都是唯一的，如何判断元素相同是使用此类集合的基础。</p>
<p>equals方法的复写需要满足以下通用约定</p>
<ul>
<li>自反性：对于任何非空引用值 x，x.equals(x) 都应返回 true，就是自己和自己比较必须相等。</li>
<li>对称性：对于任何非空引用值 x 和 y，当且仅当 y.equals(x) 返回 true 时，x.equals(y) 才应返回 true，就是x若等于y，那么y也应该等于x。</li>
<li>传递递性：对于任何非空引用值 x、y 和 z，如果 x.equals(y) 返回 true，并且 y.equals(z) 返回 true，那么 x.equals(z) 应返回 true。</li>
<li>一致性：对于任何非空引用值 x 和 y，多次调用 x.equals(y) 始终返回 true 或始终返回 false，前提是对象上 equals 比较中所用的信息没有被修改。</li>
<li>非空性：对于任何非空引用值 x，x.equals(null) 都应返回 false。</li>
</ul>
<p>如无必要不要复写equals 方法,如果复写了此方法一定要记得复写hashCode方法，因为两个对象相等，它们的hashCode也要相等，下面是equals方法的常用步骤：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">equals</span><span class="params">(Object obj)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 判断引用是否相等</span></span><br><span class="line">    <span class="keyword">if</span> (obj == <span class="keyword">this</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//判断参数类型是否正确 如果o为null也会返回false</span></span><br><span class="line">    <span class="comment">//这里判断的是class类型，也有可能是接口类型，这样就允许实现这个接口的类之间进行比较</span></span><br><span class="line">    <span class="comment">//AbstractSet，AbstractList,AbstracMap的equals方法这一步都是比较的接口</span></span><br><span class="line">    <span class="keyword">if</span> (!(obj <span class="keyword">instanceof</span> PhoneNumber)) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//类型转换</span></span><br><span class="line">    <span class="comment">// AbstractSet的类型转换  Collection&lt;?&gt; c = (Collection&lt;?&gt;) o;</span></span><br><span class="line">    PhoneNumber phoneNumber = (PhoneNumber) obj;</span><br><span class="line">    <span class="comment">// 判断重要字段的相等，如果使用的是接口，调用接口的方法获取字段</span></span><br><span class="line">    <span class="comment">// 对于基本类型 如果不是float或double 直接使用＝＝比较</span></span><br><span class="line">    <span class="comment">// float使用Float.compare(float, float), 原因参考testFloat方法</span></span><br><span class="line">    <span class="comment">//double使用Double.compare(double, double) 同上</span></span><br><span class="line">    <span class="comment">//Float.equals和Double的equals都设计autobox，影响性能</span></span><br><span class="line">    <span class="comment">//引用类型继续调用其equals方法</span></span><br><span class="line">    <span class="comment">// 上述方法也同样适用于数组元素，如果要比较整个数值，使用Arrays.equals对应的方法</span></span><br><span class="line">    <span class="comment">//对象的某些字段能为Null，为了避免NPE，使用Objects.equals(Object, Object)</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.linNum == phoneNumber.linNum &amp;&amp;</span><br><span class="line">            <span class="keyword">this</span>.prefix == phoneNumber.prefix &amp;&amp;</span><br><span class="line">            <span class="keyword">this</span>.areaCode == phoneNumber.areaCode;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当两个对象存在父子关系，并且子类添加新的值字段，在equals方法中使用instanceOf判断类型时容易破坏对称性或传递性，如Timestamp;使用getClass判断类型又违法里氏替换原则，所以避免使用继承，尝试使用组合;但如果父类是抽象的，不能实例化，则不会出现上述问题。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用组合方式替代继承Point</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ColorPoint</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Point point;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Color color;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ColorPoint</span><span class="params">(<span class="keyword">int</span> x, <span class="keyword">int</span> y, Color color)</span> </span>&#123;</span><br><span class="line">        point = <span class="keyword">new</span> Point(x, y);</span><br><span class="line">        <span class="keyword">this</span>.color = Objects.requireNonNull(color);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Point <span class="title">asPoint</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> point;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">equals</span><span class="params">(Object o)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (o == <span class="keyword">this</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (!(o <span class="keyword">instanceof</span> ColorPoint))</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        ColorPoint cp = (ColorPoint) o;</span><br><span class="line">        <span class="keyword">return</span> cp.point.equals(point) &amp;&amp; cp.color.equals(color);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>为什么不使用＝＝比较浮点值,因为有两个例外使比较不一致</p>
<ul>
<li>如果 f1 和 f2 都表示 Float.NaN，那么即使 Float.NaN == Float.NaN 的值为 false，equals 方法也将返回 true。</li>
<li>如果 f1 表示 +0.0f，而 f2 表示 -0.0f，那么即使 0.0f==-0.0f 的值为 true，equal 测试也将返回 false。</li>
</ul>
<h3 id="hashCode"><a href="#hashCode" class="headerlink" title="hashCode()"></a>hashCode()</h3><p>上文说到如果复写equals方法一定要复写hashCode方法。下面说说hash值的计算</p>
<ul>
<li>确保与equals中使用的字段一致</li>
<li>如果字段是基本类型，使用包装类计算hash值如Float.hashCode(f)</li>
<li>如果字段是引用类型，并且在equals方法中递归调用去equals方法，那么这里也递归调用其hashCode方法</li>
<li>如果字段是数组类型，对其中重要元素的hash计算上述方法同样使用，如果要计算整个数组的hash值，使用Arrays.hashCode(array)</li>
<li>质数31的选取是个传统，能尽量让不同对象拥有不同hash值，即分布均匀，</li>
<li>Objects.hash(linNum,prefix,areaCode)方法简便，但涉及可变数组的创建和拆装箱操作，性能敏感</li>
<li>此方法返回的值不应该有详细规范，如String的hashCode方法返回精确值就是一个失误</li>
</ul>
<p>如果没有明确规范，发现更好的hash方法可以在以后版本修改</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">hashCode</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> result = <span class="number">0</span>;</span><br><span class="line">    result = Short.hashCode(linNum);</span><br><span class="line">    result = <span class="number">31</span> * result + Short.hashCode(prefix);</span><br><span class="line">    result = <span class="number">31</span> * result + Short.hashCode(areaCode);</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>那些不可变对象如果hash值计算量大，需要使用缓存防止重复计算影响性能,这里线程不安全</p>
<h3 id="toString-NaN"><a href="#toString-NaN" class="headerlink" title="toString()"></a>toString()</h3><p>尽量复写toString方法，虽然不及equals和hashCode方法必要，但良好的类描述将能提供充分和友好的信息,AbstractCollection的toString为其子类统一提供集合信息的描述</p>
<p>如果要指定返回值的格式  可做如下说明 这样用户知道如何对其解析 但缺点是如果变更将导致以前的解析方式失败</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 返回格式化的电话号码"XXX-YYY-ZZZZ"</span></span><br><span class="line"><span class="comment"> * 每个大写字母表示一个数字</span></span><br><span class="line"><span class="comment"> * XXX表示区号，YYY表示前缀，ZZZZ是号码</span></span><br><span class="line"><span class="comment"> * 位数不够的用0填充，如最后一个是123将表示为0123</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> String.format(Locale.CHINA, <span class="string">"%03d-%03d-%04d"</span>, areaCode, prefix, linNum);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="clone"><a href="#clone" class="headerlink" title="clone()"></a>clone()</h3><p>如果一个class 实现了Cloneable接口 那么它应该 提供一个public clone方法</p>
<ul>
<li>这是一个毋需构造器就能创建对象的方法</li>
<li>注意：这种方式复制对象容易出错而且复杂，难以维护 仅仅在对基本类型数组的复制是可取的</li>
<li>这个方法是个浅拷贝，也就是字段到字段的复制，如果都是基本类型，那将是一步到位的，</li>
<li>但如果还有引用类型，它们指向的对象不会被拷贝，而仅仅拷贝了引用,这就会导致拷贝后的对象和被拷贝的对象不是相互独立的，这些引用指向了相同的对象，也就是任何一方的修改都在另一方得到体现</li>
<li>如果要深度拷贝，可以每个引用类型都需要实现cloneable接口和clone方法，</li>
</ul>
<p>或者使用序列化的方式将对象写到磁盘中，再通过反序列化实现克隆对象，如Apache Commons3工具类,transient修饰的字段不会被序列化。</p>
<ul>
<li>我们这个类的字段都是基础类型，clone方法比较简单,由于字段都是final，这个一个immutable（不可更改的）类，提供拷贝方法就是多余的，这里仅做演示</li>
<li>一定要先实现Cloneable接口，尽管里面什么都没有“</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">clone</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> (PhoneNumber) <span class="keyword">super</span>.clone();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (CloneNotSupportedException e) &#123;</span><br><span class="line">        <span class="comment">//实现Cloneable接口就不会抛出此异常</span></span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> AssertionError();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在实际中要实现对象拷贝，并不建议使用clone方法，而建议采用静态工厂或构造器方式提供复制操作</p>
<p>相比clone的优点：</p>
<ul>
<li>不依赖容易出错的对象创建机制;</li>
<li>不会与final字段的正确使用冲突</li>
<li>不会抛出 checked exceptions;</li>
<li>不要求类型转换</li>
</ul>
<p>比如某些集合类，以接口为参数的复制构造函数，还能实现转换复制</p>
<h3 id="Comparable"><a href="#Comparable" class="headerlink" title="Comparable"></a>Comparable</h3><p>compareTo是个很重要的方法，虽然不是Object中的，因为和其他几个方法一样广泛应用，所以放在这里解释，实现Comparabe接口，复写compareTo方法后一个对象就有了可比较性。</p>
<ul>
<li>如果此方法返回0那么equals应该返回true，如果不是一定要说明不一致性</li>
<li>HashSet依赖equals比较元素是否重复，TreeSet依赖compareTo给元素排序</li>
<li>BigDecimal这两个方法就是不一致的，BigDecimal(1.0)and BigDecimal(1.00)equals返回false，因此加入HashSet是不相同的元素<br> 但compareTo返回0，也就是大小相等，加入TreeSet就只有一个元素</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public int compareTo(PhoneNumber o) &#123;</span><br><span class="line">    int result = Short.compare(areaCode, o.areaCode);</span><br><span class="line">    if (result == 0) &#123;</span><br><span class="line">        result = Short.compare(prefix, o.prefix);</span><br><span class="line">        if (result == 0) &#123;</span><br><span class="line">            result = Short.compare(linNum, o.linNum);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注意：不要使用&lt; &gt;来比较大小，对浮点有例外，也不要使用减号，会有溢出</p>
<p>建议如上使用基本数据类型包装类的静态比较方法compare</p>
<p>也可以使用Comparator接口里面的方法，在Java8中，可以如下生成按某种顺序比较的复合比较器。内部实现是从最后一个比较方法进入向前调用的</p>
<ul>
<li>优点：在lambda表达式的帮助下逻辑清晰，表达简便</li>
<li>缺点：效率比传统的低，每层比较都创建新对象</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Comparator&lt;PhoneNumber&gt; COMPARATOR = Comparator.comparingInt(</span><br><span class="line">        (ToIntFunction&lt;PhoneNumber&gt;) phoneNumber -&gt; phoneNumber.areaCode)</span><br><span class="line">        .thenComparingInt(pn -&gt; pn.prefix)</span><br><span class="line">        .thenComparingInt(pn -&gt; pn.linNum);</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compareTo</span><span class="params">(PhoneNumber o)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> COMPARATOR.compare(<span class="keyword">this</span>, o);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在Effect Java中花了很长篇幅详细介绍了这几个方法，说明其重要性.实际开发中，编辑器、第三方库都能自动生成，但理解原理还是很重要的。</p>
<h2 id="补充"><a href="#补充" class="headerlink" title="补充"></a>补充</h2><p>  在Java中任何一个对象都具备equals(Object obj)和hashcode()这两个方法，因为他们是在Object类中定义的。  equals(Object obj)方法用来判断两个对象是否“相同”，如果“相同”则返回true，否则返回false。  hashcode()方法返回一个int数，在Object类中的默认实现是“将该对象的内部地址转换成一个整数返回”。</p>
<p>  接下来有两个个关于这两个方法的重要规范(我只是抽取了最重要的两个,其实不止两个)：</p>
<ul>
<li>规范1：若重写equals(Object obj)方法，有必要重写hashcode()方法，确保通过equals(Object obj)方法判断结果为true的两个对象具备相等的hashcode()返回值。说得简单点就是：“如果两个对象相同，那么他们的hashcode应该 相等”。不过请注意：这个只是规范，如果你非要写一个类让equals(Object obj)返回true而hashcode()返回两个不相等的值，编译和运行都是不会报错的。不过这样违反了Java规范，程序也就埋下了BUG。 </li>
<li>规范2：如果equals(Object obj)返回false，即两个对象“不相同”，并不要求对这两个对象调用hashcode()方法得到两个不相同的数。说的简单点就是：“如果两个对象不相同，他们的hashcode可能相同”。  </li>
</ul>
<p>根据这两个规范，可以得到如下推论：  </p>
<ul>
<li>1、如果两个对象equals，Java运行时环境会认为他们的hashcode一定相等。  </li>
<li>2、如果两个对象不equals，他们的hashcode有可能相等。 </li>
<li>3、如果两个对象hashcode相等，他们不一定equals。  </li>
<li>4、如果两个对象hashcode不相等，他们一定不equals。 </li>
</ul>
<p>这样我们就可以推断Java运行时环境是怎样判断HashSet和HastMap中的两个对象相同或不同了。我的推断是：先判断hashcode是否相等，再判断是否equals。 </p>
<p> ‘\==’是用来比较两个变量（基本类型和对象类型）的值是否相等的， 如果两个变量是基本类型的，那很容易，直接比较值就可以了。如果两个变量是对象类型的，那么它还是比较值，只是它比较的是这两个对象在栈中的引用（即地址）。 对象是放在堆中的，栈中存放的是对象的引用（地址）。由此可见’\==’是对栈中的值进行比较的。如果要比较堆中对象的内容是否相同，那么就要重写equals方法了。 2. Object类中的equals方法就是用’\==’来比较的，所以如果没有重写equals方法，equals和==是等价的。 通常我们会重写equals方法，让equals比较两个对象的内容，而不是比较对象的引用（地址）因为往往我们觉得比较对象的内容是否相同比比较对象的引用（地址）更有意义。 3. Object类中的hashCode是返回对象在内存中地址转换成的一个int值（可以就当做地址看）。所以如果没有重写hashCode方法，任何对象的hashCode都是不相等的。通常在集合类的时候需要重写hashCode方法和equals方法，因为如果需要给集合类（比如：HashSet）添加对象，那么在添加之前需要查看给集合里是否已经有了该对象，比较好的方式就是用hashCode。 4. 注意的是String、Integer、Boolean、Double等这些类都重写了equals和hashCode方法，这两个方法是根据对象的内容来比较和计算hashCode的。（详细可以查看jdk下的String.java源代码），所以只要对象的基本类型值相同，那么hashcode就一定相同。</p>
<ol>
<li>equals()相等的两个对象，hashcode()一般是相等的，最好在重写equals()方法时，重写hashcode()方法； equals()不相等的两个对象，却并不能证明他们的hashcode()不相等。换句话说，equals()方法不相等的两个对象，hashcode()有可能相等。 反过来：hashcode()不等，一定能推出equals()也不等；hashcode()相等，equals()可能相等，也可能不等。在object类中，hashcode()方法是本地方法，返回的是对象的引用（地址值），而object类中的equals()方法比较的也是两个对象的引用（地址值），如果equals()相等，说明两个对象地址值也相等，当然hashcode()也就相等了。</li>
</ol>

      
    </div>

    

    
    
    

    
        
    

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div>您的支持将鼓励我继续创作</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/xieyuanhui/images/wechatpay.png" alt="xieyuanhui 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/xieyuanhui/images/alipay.jpg" alt="xieyuanhui 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/xieyuanhui/tags/Object/" rel="tag"># Object</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div class="social_share">
            
            
              <div id="needsharebutton-postbottom">
                <span class="btn">
                  <i class="fa fa-share-alt" aria-hidden="true"></i>
                </span>
              </div>
            
            
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/xieyuanhui/2019/08/04/进程间的五种通信方式介绍/" rel="next" title="进程间的五种通信方式介绍">
                <i class="fa fa-chevron-left"></i> 进程间的五种通信方式介绍
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/xieyuanhui/2019/08/05/线程池ThreadPoolExecutor详解/" rel="prev" title="线程池ThreadPoolExecutor详解">
                线程池ThreadPoolExecutor详解 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/xieyuanhui/images/deer.png" alt="xieyuanhui">
            
              <p class="site-author-name" itemprop="name">xieyuanhui</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/xieyuanhui/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/xieyuanhui/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">16</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/xieyuanhui/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">114</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/xieyuanhui/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="/xieyuanhui/yuanhxie@163.com" title="E-Mail &rarr; yuanhxie@163.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#equals-Object-o"><span class="nav-text">equals(Object o)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#hashCode"><span class="nav-text">hashCode()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#toString-NaN"><span class="nav-text">toString()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#clone"><span class="nav-text">clone()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Comparable"><span class="nav-text">Comparable</span></a></li></ol><li class="nav-item nav-level-2"><a class="nav-link" href="#补充"><span class="nav-text">补充</span></a></li></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xieyuanhui</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">站点总字数：</span>
    
    <span title="站点总字数">749k</span>
  

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    
    <span title="站点阅读时长">11:21</span>
  
</div>


  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.1.0</div>


<div><span id="sitetime"></span>
<script language="javascript">
  function siteTime(){
    window.setTimeout("siteTime()", 1000);
    var seconds = 1000;
    var minutes = seconds * 60;
    var hours = minutes * 60;
    var days = hours * 24;
    var years = days * 365;
    var today = new Date();
    var todayYear = today.getFullYear();
    var todayMonth = today.getMonth()+1;
    var todayDate = today.getDate();
    var todayHour = today.getHours();
    var todayMinute = today.getMinutes();
    var todaySecond = today.getSeconds();
    /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
    year - 作为date对象的年份，为4位年份值
    month - 0-11之间的整数，做为date对象的月份
    day - 1-31之间的整数，做为date对象的天数
    hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
    minutes - 0-59之间的整数，做为date对象的分钟数
    seconds - 0-59之间的整数，做为date对象的秒数
    microseconds - 0-999之间的整数，做为date对象的毫秒数 */
    var t1 = Date.UTC(2019,04,09,15,00,00); //北京时间2018-2-13 00:00:00
    var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
    var diff = t2-t1;
    var diffYears = Math.floor(diff/years);
    var diffDays = Math.floor((diff/days)-diffYears*365);
    var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
    var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
    var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
    document.getElementById("sitetime").innerHTML=" xieyuanhui的个人笔记已运行"+/*diffYears+" 年 "+*/diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
  }/*因为建站时间还没有一年，就将之注释掉了。需要的可以取消*/
  siteTime();
</script></div>



<div>

  <div class="theme-info">
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
    <span class="post-meta-divider">|</span>
    <span id="busuanzi_container_site_uv">本站访客数<span id="busuanzi_value_site_uv"></span>人</span>
  </div>

</div>

        






  <div>
    <script type="text/javascript">
	    var cnzz_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
	    document.write(unescape("%3Cspan id='cnzz_stat_icon_1277235632'%3E%3C/span%3E%3Cscript 
	    src='" + cnzz_protocol + "s23.cnzz.com/z_stat.php%3Fid%3D1277235632%26show%3Dpic' 
	    type='text/javascript'%3E%3C/script%3E"));
    </script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  



  
    
    
  
  <script color="0,0,255" opacity="0.5" zindex="-1" count="99" src="/xieyuanhui/lib/canvas-nest/canvas-nest.min.js"></script>













  
  <script src="/xieyuanhui/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/xieyuanhui/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/xieyuanhui/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script src="/xieyuanhui/lib/fancybox/source/jquery.fancybox.pack.js"></script>


  


  <script src="/xieyuanhui/js/utils.js?v=7.1.0"></script>

  <script src="/xieyuanhui/js/motion.js?v=7.1.0"></script>



  
  


  <script src="/xieyuanhui/js/affix.js?v=7.1.0"></script>

  <script src="/xieyuanhui/js/schemes/pisces.js?v=7.1.0"></script>



  
  <script src="/xieyuanhui/js/scrollspy.js?v=7.1.0"></script>
<script src="/xieyuanhui/js/post-details.js?v=7.1.0"></script>



  


  <script src="/xieyuanhui/js/next-boot.js?v=7.1.0"></script>


  

  

  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/xieyuanhui/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  
  
  <script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log('LeanCloud Counter Error: ' + responseJSON.code + ' ' + responseJSON.error);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'q2BU0OM2W8i5nARddHRKQOvm-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'q2BU0OM2W8i5nARddHRKQOvm-gzGzoHsz',
                'X-LC-Key': 'hLTPk12Jmt8atnC9cePjTwQH',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script>



  

  
  

  
  

  
    
      <script type="text/x-mathjax-config">
  

  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$', '$'], ['\\(', '\\)'] ],
      processEscapes: true,
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      
      equationNumbers: {
        autoNumber: 'AMS'
      }
    }
  });
  MathJax.Hub.Register.StartupHook('TeX Jax Ready', function() {
    MathJax.InputJax.TeX.prefilterHooks.Add(function(data) {
      if (data.display) {
        var next = data.script.nextSibling;
        while (next && next.nodeName.toLowerCase() === '#text') { next = next.nextSibling }
        if (next && next.nodeName.toLowerCase() === 'br') { next.parentNode.removeChild(next) }
      }
    });
  });
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for (i = 0; i < all.length; i += 1) {
      document.getElementById(all[i].inputID + '-Frame').parentNode.className += ' has-jax';
    }
  });
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"></script>

    
  


  

  

  

  

  
  
  
  <script src="/xieyuanhui/lib/needsharebutton/needsharebutton.js"></script>
  <script>
    
      pbOptions = {};
      
        pbOptions.iconStyle = "box";
      
        pbOptions.boxForm = "horizontal";
      
        pbOptions.position = "bottomCenter";
      
        pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
        flOptions.iconStyle = "box";
      
        flOptions.boxForm = "horizontal";
      
        flOptions.position = "middleRight";
      
        flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>


  

  

  

  

  

  


  
  <script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script><!-- hexo-inject:begin --><!-- Begin: Injected MathJax -->
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({"tex2jax":{"inlineMath":[["$","$"],["\\(","\\)"]],"skipTags":["script","noscript","style","textarea","pre","code"],"processEscapes":true},"TeX":{"equationNumbers":{"autoNumber":"AMS"}}});
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
      all[i].SourceElement().parentNode.className += ' has-jax';
    }
  });
</script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js">
</script>
<!-- End: Injected MathJax -->
<!-- hexo-inject:end -->
  
</body>
</html>
